/**
 * 遍历树节点
 * @param tree
 * @param callback
 * @param parents
 */
 export const forEach = (tree = [], callback = () => {}, parents = [], childrenField = 'children') => {
  (tree || []).forEach((item) => {
    callback(item, parents);
    forEach(item[childrenField], callback, [item, ...parents]);
  });
};

/**
 * 将数组转换为树结构
 * @param arr
 * @param id
 * @param parentId
 * @param rootKeyValue
 * @returns {[]}
 */
export function arrayToTree (arr, { id, parentId } = { id: 'id', parentId: 'parentId' }, rootKeyValue = '') {
  const tree = [];

  arr.sort((a, b) => a[id].localeCompare(b[id])).forEach((item) => {
    if (item[parentId] === rootKeyValue) {
      tree.push({ ...item });
    } else {
      forEach(tree, (parent) => {
        if (item[parentId] === parent[id]) {
          parent.children = [...(parent.children || []), item];
        }
      });
    }
  });

  return tree;
}

/**
 * 展开树
 * @param tree
 * @returns {[]}
 */
export function flattenTree (tree = []) {
  const flattened = [];

  forEach(tree, (item, parents) => {
    flattened.push({
      ...item,
      parents
    });
  });

  return flattened;
}

/**
 * 获取叶子节点
 * @param tree
 * @returns {[]}
 */
export function getLeafNodes (tree = []) {
  const leafNodes = [];

  forEach(tree, (item) => !item.children && leafNodes.push(item));

  return leafNodes;
}

/**
 * 查找树节点
 * @param tree
 * @param func
 * @returns {*}
 */
export function find (tree = [], func) {
  return flattenTree(tree).find((item) => func(item));
}
/*
 *@description: 查找树上所有的叶子节点
 *@author: wudandan
 *@date: 2021-03-11 14:21:13
*/
export function findTreeLeaf (arr = [], newArr = []) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].childList.length < 1) {
      newArr.push(arr[i]);
    } else {
      if (arr[i].childList) {
        findTreeLeaf(arr[i].childList, newArr);
      }
    }
  }
  return newArr;
}
/*
 *@description: 根据id查找树上的节点
 *@author: wudandan
 *@date: 2021-03-11 14:24:45
*/
export function findTreeNodeById (arr = [], newArr = [], id) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].id === id && newArr.length < 1) {
      newArr.push(arr[i]);
    } else {
      if (arr[i].childList) {
        findTreeNodeById(arr[i].childList, newArr, id);
      }
    }
  }
  return newArr;
}
/**
 * 获取所有子节点数据
 * @param {*} data
 * @returns
 */
export function getAllLeaf (nodes, result = []) {
  for (var i = 0, length = nodes.length; i < length; i++) {
    if (!nodes[i].childList || nodes[i].childList.length === 0) {
      result.push(nodes[i]);
    } else {
      result = getAllLeaf(nodes[i].childList, result);
    }
  }
  return result;
}
